'use client';

import { useState } from 'react';
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { AlertCircle, Info, User, FileText, Plus, RefreshCw, Cloud } from "lucide-react";
import { useUsers, useCreateUser, useUser } from "@/shared/api/users";
import { useInfinitePosts } from "@/shared/api/posts";
import { useWeather } from "@/shared/api/weather";
import { useNotes, useCreateNote, useDeleteNote } from "@/shared/api/notes";

// Define TypeScript interfaces
interface Note {
    id: number;
    content: string;
}

interface Post {
    id: number;
    title: string;
    body: string;
}

export default function TanStackLearnPageClient() {
    const [selectedUserId, setSelectedUserId] = useState<number | null>(null);
    const [newUserName, setNewUserName] = useState('');
    const [newNoteContent, setNewNoteContent] = useState('');
    const [weatherCity, setWeatherCity] = useState('Beijing');
    const [searchCity, setSearchCity] = useState('Beijing');
    const [deletingNoteId, setDeletingNoteId] = useState<number | null>(null); // Track specific note being deleted

    // Users hooks
    const { data: users, isLoading: usersLoading, error: usersError } = useUsers();
    // Only call useUser when selectedUserId is a valid number
    const { data: userDetails, isLoading: userDetailsLoading, error: userDetailsError } = useUser(selectedUserId || 0, {
        enabled: selectedUserId !== null && selectedUserId > 0
    });
    const { mutate: createUserMutation, isPending: isCreatingUser, error: createUserError } = useCreateUser();

    // Posts hooks
    const {
        data: postsData,
        fetchNextPage,
        hasNextPage,
        isFetchingNextPage,
        status: postsStatus,
        isPending: isPostsPending,
    } = useInfinitePosts({ page: 1, limit: 5 });

    // Weather hooks
    const { data: weatherData, isLoading: weatherLoading, error: weatherError } = useWeather({ city: searchCity });

    // Notes hooks
    const { data: notes, isLoading: notesLoading, error: notesError } = useNotes();
    const { mutate: createNoteMutation, isPending: isCreatingNote } = useCreateNote();
    const { mutate: deleteNoteMutation } = useDeleteNote();

    const handleCreateUser = () => {
        if (newUserName.trim()) {
            createUserMutation(
                { name: newUserName, email: `${newUserName}@example.com` },
                {
                    onSuccess: () => {
                        setNewUserName('');
                    }
                }
            );
        }
    };

    const handleCreateNote = () => {
        if (newNoteContent.trim()) {
            createNoteMutation(
                { content: newNoteContent },
                {
                    onSuccess: () => {
                        setNewNoteContent('');
                    }
                }
            );
        }
    };

    const handleDeleteNote = (id: number) => {
        setDeletingNoteId(id); // Track the specific note being deleted
        deleteNoteMutation(id, {
            onSuccess: () => {
                setDeletingNoteId(null); // Clear the deleting state on success
            },
            onError: () => {
                setDeletingNoteId(null); // Clear the deleting state on error
            }
        });
    };

    const handleSearchWeather = () => {
        setSearchCity(weatherCity);
    };

    return (
        <div className="container mx-auto py-8">
            <Card className="mb-8">
                <CardHeader className="text-center">
                    <CardTitle className="text-3xl font-bold">TanStack Query 学习指南</CardTitle>
                </CardHeader>
            </Card>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                {/* Users Section */}
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <User className="h-5 w-5" />
                            用户列表 (useUsers)
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        {usersLoading ? (
                            <div className="space-y-2">
                                <Skeleton className="h-12 w-full" />
                                <Skeleton className="h-12 w-full" />
                                <Skeleton className="h-12 w-full" />
                            </div>
                        ) : usersError ? (
                            <Alert variant="destructive">
                                <AlertCircle className="h-4 w-4" />
                                <AlertTitle>错误</AlertTitle>
                                <AlertDescription>
                                    加载用户失败: {usersError.message}
                                </AlertDescription>
                            </Alert>
                        ) : (
                            <div className="space-y-2">
                                {users?.map((user) => (
                                    <Card
                                        key={user.id}
                                        className={`cursor-pointer transition-colors ${
                                            selectedUserId === user.id ? 'border-primary' : ''
                                        }`}
                                        onClick={() => setSelectedUserId(user.id)}
                                    >
                                        <CardContent className="p-4">
                                            <p className="font-medium">{user.name}</p>
                                            <p className="text-sm text-muted-foreground">{user.email}</p>
                                        </CardContent>
                                    </Card>
                                ))}
                            </div>
                        )}
                    </CardContent>
                </Card>

                {/* User Details Section */}
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <User className="h-5 w-5" />
                            用户详情 (useUser)
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        {selectedUserId ? (
                            <>
                                {userDetailsLoading ? (
                                    <div className="space-y-2">
                                        <Skeleton className="h-6 w-3/4" />
                                        <Skeleton className="h-4 w-full" />
                                        <Skeleton className="h-4 w-full" />
                                        <Skeleton className="h-4 w-2/3" />
                                    </div>
                                ) : userDetailsError ? (
                                    <Alert variant="destructive">
                                        <AlertCircle className="h-4 w-4" />
                                        <AlertTitle>错误</AlertTitle>
                                        <AlertDescription>
                                            加载用户详情失败: {userDetailsError.message}
                                        </AlertDescription>
                                    </Alert>
                                ) : (
                                    <div className="space-y-4">
                                        <div>
                                            <h3 className="text-lg font-medium">{userDetails?.name}</h3>
                                            <p className="text-muted-foreground">用户名: {userDetails?.username}</p>
                                        </div>
                                        <Separator />
                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                            <div>
                                                <Label>邮箱</Label>
                                                <p className="text-sm">{userDetails?.email}</p>
                                            </div>
                                            <div>
                                                <Label>电话</Label>
                                                <p className="text-sm">{userDetails?.phone}</p>
                                            </div>
                                            <div>
                                                <Label>网站</Label>
                                                <p className="text-sm">{userDetails?.website}</p>
                                            </div>
                                            <div>
                                                <Label>地址</Label>
                                                <p className="text-sm">
                                                    {userDetails?.address?.street}, {userDetails?.address?.city}
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                )}
                            </>
                        ) : (
                            <Alert>
                                <Info className="h-4 w-4" />
                                <AlertTitle>提示</AlertTitle>
                                <AlertDescription>
                                    请选择一个用户查看详细信息
                                </AlertDescription>
                            </Alert>
                        )}
                    </CardContent>
                </Card>

                {/* Create User Section */}
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Plus className="h-5 w-5" />
                            创建用户 (useCreateUser)
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="space-y-4">
                            <div className="space-y-2">
                                <Label htmlFor="username">用户名</Label>
                                <Input
                                    id="username"
                                    value={newUserName}
                                    onChange={(e) => setNewUserName(e.target.value)}
                                    placeholder="输入用户名"
                                    disabled={isCreatingUser}
                                />
                            </div>
                            <Button
                                onClick={handleCreateUser}
                                disabled={isCreatingUser || !newUserName.trim()}
                                className="w-full"
                            >
                                {isCreatingUser ? (
                                    <>
                                        <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                                        创建中...
                                    </>
                                ) : (
                                    <>
                                        <Plus className="mr-2 h-4 w-4" />
                                        创建用户
                                    </>
                                )}
                            </Button>
                        </div>

                        {createUserError && (
                            <Alert variant="destructive" className="mt-4">
                                <AlertCircle className="h-4 w-4" />
                                <AlertTitle>错误</AlertTitle>
                                <AlertDescription>
                                    创建用户失败: {createUserError.message}
                                </AlertDescription>
                            </Alert>
                        )}
                    </CardContent>
                </Card>

                {/* Posts Section (useInfinitePosts) */}
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <FileText className="h-5 w-5" />
                            文章列表 (useInfinitePosts)
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        {isPostsPending? (
                            <div className="space-y-2">
                                <Skeleton className="h-16 w-full" />
                                <Skeleton className="h-16 w-full" />
                                <Skeleton className="h-16 w-full" />
                            </div>
                        ) : postsStatus === 'error' ? (
                            <Alert variant="destructive">
                                <AlertCircle className="h-4 w-4" />
                                <AlertTitle>错误</AlertTitle>
                                <AlertDescription>
                                    加载文章失败
                                </AlertDescription>
                            </Alert>
                        ) : (
                            <>
                                <div className="space-y-4">
                                    {postsData?.pages.map((page, i) => (
                                        <div key={i} className="space-y-3">
                                            {page.map((post: Post) => (
                                                <Card key={post.id}>
                                                    <CardHeader className="p-4">
                                                        <CardTitle className="text-base">{post.title}</CardTitle>
                                                    </CardHeader>
                                                    <CardContent className="p-4 pt-0">
                                                        <p className="text-sm text-muted-foreground line-clamp-2">{post.body}</p>
                                                    </CardContent>
                                                </Card>
                                            ))}
                                        </div>
                                    ))}
                                </div>

                                <div className="mt-4">
                                    <Button
                                        onClick={() => fetchNextPage()}
                                        disabled={!hasNextPage || isFetchingNextPage}
                                        variant="outline"
                                        className="w-full"
                                    >
                                        {isFetchingNextPage ? (
                                            <>
                                                <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                                                加载更多...
                                            </>
                                        ) : hasNextPage ? (
                                            '加载更多'
                                        ) : (
                                            '没有更多内容'
                                        )}
                                    </Button>
                                </div>
                            </>
                        )}
                    </CardContent>
                </Card>

                {/* Weather Section (useWeather) */}
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Cloud className="h-5 w-5" />
                            天气信息 (useWeather)
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="space-y-4">
                            <div className="flex gap-2">
                                <Input
                                    value={weatherCity}
                                    onChange={(e) => setWeatherCity(e.target.value)}
                                    placeholder="输入城市名"
                                />
                                <Button onClick={handleSearchWeather}>查询</Button>
                            </div>

                            {weatherLoading ? (
                                <Skeleton className="h-24 w-full" />
                            ) : weatherError ? (
                                <Alert variant="destructive">
                                    <AlertCircle className="h-4 w-4" />
                                    <AlertTitle>错误</AlertTitle>
                                    <AlertDescription>
                                        获取天气信息失败: {weatherError.message}
                                    </AlertDescription>
                                </Alert>
                            ) : weatherData ? (
                                <Card>
                                    <CardContent className="p-4">
                                        <div className="flex justify-between items-center">
                                            <div>
                                                <h3 className="text-xl font-bold">{weatherData.location}</h3>
                                                <p className="text-2xl">{weatherData.temp_c}°C</p>
                                            </div>
                                            <div className="text-right">
                                                <p className="text-muted-foreground">{weatherData.condition}</p>
                                            </div>
                                        </div>
                                    </CardContent>
                                </Card>
                            ) : null}
                        </div>
                    </CardContent>
                </Card>

                {/* Notes Section (useNotes, useCreateNote, useDeleteNote) */}
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <FileText className="h-5 w-5" />
                            笔记 (useNotes, useCreateNote, useDeleteNote)
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="space-y-4">
                            <div className="flex gap-2">
                                <Input
                                    value={newNoteContent}
                                    onChange={(e) => setNewNoteContent(e.target.value)}
                                    placeholder="输入笔记内容"
                                    disabled={isCreatingNote}
                                />
                                <Button
                                    onClick={handleCreateNote}
                                    disabled={isCreatingNote || !newNoteContent.trim()}
                                >
                                    {isCreatingNote ? (
                                        <>
                                            <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                                            创建中...
                                        </>
                                    ) : (
                                        '添加'
                                    )}
                                </Button>
                            </div>

                            {notesLoading ? (
                                <div className="space-y-2">
                                    <Skeleton className="h-12 w-full" />
                                    <Skeleton className="h-12 w-full" />
                                    <Skeleton className="h-12 w-full" />
                                </div>
                            ) : notesError ? (
                                <Alert variant="destructive">
                                    <AlertCircle className="h-4 w-4" />
                                    <AlertTitle>错误</AlertTitle>
                                    <AlertDescription>
                                        加载笔记失败: {notesError.message}
                                    </AlertDescription>
                                </Alert>
                            ) : (
                                <div className="space-y-2">
                                    {notes?.map((note: Note) => (
                                        <Card key={note.id}>
                                            <CardContent className="p-4 flex justify-between items-center">
                                                <p className="font-medium">{note.content}</p>
                                                <Button
                                                    variant="destructive"
                                                    size="sm"
                                                    onClick={() => handleDeleteNote(note.id)}
                                                    disabled={deletingNoteId === note.id} // Only disable the specific note being deleted
                                                >
                                                    {deletingNoteId === note.id ? '删除中...' : '删除'} {/* Only show "删除中..." for the specific note */}
                                                </Button>
                                            </CardContent>
                                        </Card>
                                    ))}
                                </div>
                            )}
                        </div>
                    </CardContent>
                </Card>
            </div>

            {/* Features Section */}
            <Card className="mt-12">
                <CardHeader>
                    <CardTitle className="text-2xl">TanStack Query 核心特性</CardTitle>
                </CardHeader>
                <CardContent>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Badge variant="secondary">1</Badge>
                                    自动缓存和更新
                                </CardTitle>
                            </CardHeader>
                            <CardContent>
                                <CardDescription>
                                    TanStack Query 自动缓存请求结果，避免重复请求，并在适当的时候自动更新数据。
                                </CardDescription>
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Badge variant="secondary">2</Badge>
                                    后台数据同步
                                </CardTitle>
                            </CardHeader>
                            <CardContent>
                                <CardDescription>
                                    数据会在后台自动同步，确保用户界面始终显示最新的数据。
                                </CardDescription>
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Badge variant="secondary">3</Badge>
                                    请求去重
                                </CardTitle>
                            </CardHeader>
                            <CardContent>
                                <CardDescription>
                                    相同的请求会被自动去重，避免同一时间发送多个相同的请求。
                                </CardDescription>
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Badge variant="secondary">4</Badge>
                                    错误重试机制
                                </CardTitle>
                            </CardHeader>
                            <CardContent>
                                <CardDescription>
                                    当请求失败时，TanStack Query 会自动重试，提高应用的稳定性。
                                </CardDescription>
                            </CardContent>
                        </Card>
                    </div>
                </CardContent>
            </Card>

            {/* Installation Guide */}
            <Card className="mt-8">
                <CardHeader>
                    <CardTitle className="text-2xl">安装和使用</CardTitle>
                </CardHeader>
                <CardContent>
                    <div className="space-y-6">
                        <div>
                            <CardTitle className="text-lg mb-2 flex items-center gap-2">
                                <Badge>1</Badge>
                                安装依赖
                            </CardTitle>
                            <Card className="bg-muted">
                                <CardContent className="p-4">
                                    <code className="text-sm">npm install @tanstack/react-query @tanstack/react-query-devtools</code>
                                </CardContent>
                            </Card>
                        </div>

                        <div>
                            <CardTitle className="text-lg mb-2 flex items-center gap-2">
                                <Badge>2</Badge>
                                配置 Provider
                            </CardTitle>
                            <Card className="bg-muted">
                                <CardContent className="p-4">
                  <pre className="text-sm overflow-x-auto">
                    <code>{`// app/layout.tsx
import { Providers } from './providers';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html>
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}`}</code>
                  </pre>
                                </CardContent>
                            </Card>
                        </div>

                        <div>
                            <CardTitle className="text-lg mb-2 flex items-center gap-2">
                                <Badge>3</Badge>
                                创建 Providers 组件
                            </CardTitle>
                            <Card className="bg-muted">
                                <CardContent className="p-4">
                  <pre className="text-sm overflow-x-auto">
                    <code>{`// app/providers.tsx
'use client';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

export function Providers({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(() => new QueryClient());

  return (
    <QueryClientProvider client={queryClient}>
      {children}
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  );
}`}</code>
                  </pre>
                                </CardContent>
                            </Card>
                        </div>

                        <div>
                            <CardTitle className="text-lg mb-2 flex items-center gap-2">
                                <Badge>4</Badge>
                                在组件中使用
                            </CardTitle>
                            <Card className="bg-muted">
                                <CardContent className="p-4">
                  <pre className="text-sm overflow-x-auto">
                    <code>{`// 在你的组件中
import { useUsers, useCreateUser } from "@/shared/api/users";

function MyComponent() {
  const { data: users, isLoading, error } = useUsers();
  const { mutate: createUser, isPending } = useCreateUser();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>An error occurred: {error.message}</div>;
  
  return <div>{/* 渲染数据 */}</div>;
}`}</code>
                  </pre>
                                </CardContent>
                            </Card>
                        </div>
                    </div>
                </CardContent>
            </Card>
        </div>
    );
}
